package thread.blockingQueue;

public class MyBlockingQueue {
    private final String[] data = new String[1000];
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;
    public synchronized void put(String elem) throws InterruptedException {
        while(size == data.length) {
            //使用while循环，如果wait被interrup()唤醒，抛出异常后，队列为满，要继续睡觉
            this.wait();
        }
        data[tail++] = elem;
        if(tail == data.length) {
            tail = 0;
        }
        size++;
        this.notify();
    }
    public synchronized String take() throws InterruptedException {
        while(size == 0) {
            //使用while循环，如果wait被interrup()唤醒，抛出异常后，队列为空，要继续睡觉
            this.wait();
        }
        String ret = data[head++];
        if(head == data.length) {
            head = 0;
        }
        size--;
        this.notify();
        return ret;
    }
}
